package com.artisan.common.utils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 * Created by  on 2017/6/17.
 */
public class TimeFormatUtil {

	private static final Logger log = LogManager.getLogger(TimeFormatUtil.class);

	private static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

	private static final String YYYY_MM_DD = "yyyy-MM-dd";

	private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 将日期转换成年月日时分格式
	 * @param date
	 * @return
	 */
	public static String dateToStrNoSecond(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM);
		return sdf.format(date);
	}

	/**
	 * 日期转换成年月日时分秒格式
	 * @param date
	 * @return
	 */
	public static String dateToStrFull(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return sdf.format(date);
	}

	/**
	 * 将时间转换成年月日格式字符串
	 * @param date
	 * @return
	 */
	public static String dateToStrToDay(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
		return sdf.format(date);
	}

	/**
	 *
	 * @param dateStr
	 * @return
	 */
	public static Date parseDateToMin(String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM);
		try {
			Date date = sdf.parse(dateStr);
			return date;
		} catch (ParseException e) {
			log.error("Parse dateStr({}) to date failed." , e);
			return null;
		}
	}

	/**
	 *
	 * @param dateStr
	 * @return
	 */
	public static Date parseDate(String dateStr) {
		SimpleDateFormat sdf = null;
		try {
			if (dateStr != null) {
				if (dateStr.indexOf(":") > 0) {
					sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
					return sdf.parse(dateStr);
				} else {
					sdf = new SimpleDateFormat(YYYY_MM_DD);
					return sdf.parse(dateStr);
				}
			}
			return null;
		} catch (ParseException e) {
			log.error("Parse dateStr({}) to date failed.", e);
			return null;
		}
	}
}

